package com.xuanzheng.company.service.impl;

import com.xuanzheng.company.dao.UserDao;
import com.xuanzheng.company.dao.impl.UserDaoImpl;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.UserService;
import com.xuanzheng.company.util.PasswordUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();

    @Override
    public User login(String phone, String password, int role) {
        User user = userDao.findByPhone(phone);
        if (user != null && PasswordUtil.verifyPassword(password, user.getPassword()) && user.getRole() == role) {
            // 检查用户状态，禁用状态的用户不允许登录
            if (user.getStatus() == 0) {
                return null;
            }
            return user;
        }
        return null;
    }

    @Override
    public boolean adminLogin(String adminId, String password) {
        // 对输入的密码进行MD5加密
        String encryptedPassword = PasswordUtil.encryptPassword(password);
        // 直接使用加密后的密码进行验证
        return userDao.checkAdmin(adminId, encryptedPassword);
    }

    @Override
    public String registerNormalUser(User user) {
        // 检查手机号是否已存在
        if (isPhoneExist(user.getPhone())) {
            return null;
        }
        
        // 设置用户角色为普通用户
        user.setRole(0);
        
        // 加密密码
        String encryptedPassword = PasswordUtil.encryptPassword(user.getPassword());
        user.setPassword(encryptedPassword);
        
        // 添加用户
        boolean success = userDao.addNormalUser(user);
        if (success) {
            return user.getId();
        }
        return null;
    }

    @Override
    public String registerCompanyManager(User user) {
        // 检查手机号是否已存在
        if (isPhoneExist(user.getPhone())) {
            return null;
        }
        
        // 设置用户角色为公司负责人
        user.setRole(1);
        
        // 加密密码
        String encryptedPassword = PasswordUtil.encryptPassword(user.getPassword());
        user.setPassword(encryptedPassword);
        
        // 添加用户
        boolean success = userDao.addCompanyManager(user);
        if (success) {
            return user.getId();
        }
        return null;
    }

    @Override
    public boolean resetPassword(String phone, String name, String idCard, String newPassword) {
        // 检查手机号是否存在
        if (!isPhoneExist(phone)) {
            return false;
        }
        
        // 加密新密码
        String encryptedPassword = PasswordUtil.encryptPassword(newPassword);
        
        // 更新密码
        return userDao.updatePassword(phone, encryptedPassword);
    }

    @Override
    public boolean isPhoneExist(String phone) {
        User user = userDao.findByPhone(phone);
        return user != null;
    }
    
    @Override
    public User findUserByNameAndIdCard(String name, String idCard) {
        return userDao.findByNameAndIdCard(name, idCard);
    }
    
    @Override
    public User findUserByNameAndIdCardAndPhone(String name, String idCard, String phone) {
        return userDao.findByNameAndIdCardAndPhone(name, idCard, phone);
    }
    
    @Override
    public boolean updateUser(User user) {
        return userDao.updateUser(user);
    }
    
    @Override
    public User findById(String id) {
        return userDao.findById(id);
    }
    
    @Override
    public User findByPhone(String phone) {
        return userDao.findByPhone(phone);
    }
    
    @Override
    public List<User> getAllUsers() {
        return userDao.getAllUsers();
    }
    
    @Override
    public List<User> searchUsers(String keyword, String searchType) {
        if (keyword == null || keyword.trim().isEmpty()) {
            // 如果没有关键词，返回所有用户
            return userDao.getAllUsers();
        }
        
        keyword = keyword.trim();
        
        // 根据不同的搜索类型进行搜索
        switch (searchType) {
            case "name":
                return userDao.findUsersByName(keyword);
            case "phone":
                return userDao.findUsersByPhone(keyword);
            case "idCard":
                return userDao.findUsersByIdCard(keyword);
            default:
                // 默认按姓名搜索
                return userDao.findUsersByName(keyword);
        }
    }
    
    @Override
    public boolean updateUserStatus(String id, int status) {
        // 检查状态值是否合法
        if (status != 0 && status != 1) {
            return false;
        }
        
        return userDao.updateUserStatus(id, status);
    }
    
    @Override
    public boolean deleteUserById(String id) {
        // System.out.println("UserServiceImpl.deleteUserById - 开始处理, 用户ID: " + id);
        if (id == null || id.trim().isEmpty()) {
            // System.out.println("UserServiceImpl.deleteUserById - 用户ID为空，返回失败");
            return false;
        }
        boolean result = userDao.deleteUserById(id);
        // System.out.println("UserServiceImpl.deleteUserById - 处理完成, 结果: " + result);
        return result;
    }
    
    @Override
    public Map<String, Object> updateAdminPassword(String adminId, String oldPassword, String newPassword) {
        Map<String, Object> result = new HashMap<>();
        
        // System.out.println("UserServiceImpl.updateAdminPassword - adminId: " + adminId);
        // System.out.println("UserServiceImpl.updateAdminPassword - oldPassword: " + oldPassword);
        
        // 获取数据库中存储的密码
        String storedPassword = userDao.getAdminPassword(adminId);
        // System.out.println("UserServiceImpl.updateAdminPassword - storedPassword: " + storedPassword);
        
        if (storedPassword == null) {
            result.put("success", false);
            result.put("message", "管理员账号不存在");
            return result;
        }
        
        // 对旧密码进行加密，然后与数据库中存储的密码比较
        String encryptedOldPassword = PasswordUtil.encryptPassword(oldPassword);
        // System.out.println("UserServiceImpl.updateAdminPassword - encryptedOldPassword: " + encryptedOldPassword);
        // System.out.println("UserServiceImpl.updateAdminPassword - 密码匹配: " + encryptedOldPassword.equals(storedPassword));
        
        if (!encryptedOldPassword.equals(storedPassword)) {

            result.put("success", false);
            result.put("message", "旧密码不正确");
            return result;
        }
        
        // 验证新密码是否符合规则：不少于6位
        if (newPassword == null || newPassword.length() < 6) {
            result.put("success", false);
            result.put("message", "新密码长度不能少于6位");
            return result;
        }
        
        // 验证新密码不能与旧密码相同
        if (newPassword.equals(oldPassword)) {
            result.put("success", false);
            result.put("message", "新密码不能与旧密码相同");
            return result;
        }
        
        // 对新密码进行加密
        String encryptedNewPassword = PasswordUtil.encryptPassword(newPassword);
        
        // 更新密码
        boolean updateSuccess = userDao.updateAdminPassword(adminId, encryptedNewPassword);
        
        if (updateSuccess) {
            result.put("success", true);
            result.put("message", "密码更新成功");
        } else {
            result.put("success", false);
            result.put("message", "密码更新失败，请稍后重试");
        }
        
        return result;
    }
} 